package com.bw.main

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.bw.base.path.RouterPath
import com.bw.common.event.CustomEvent
import com.bw.common.view.BaseMvvmActivity
import com.bw.main.databinding.ActivityMainBinding
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import dagger.hilt.android.AndroidEntryPoint

/**
 * 业务：
 * 1.承载所有子模块
 * 2.权限校验
 * 3.版本升级
 * 4.消息提示
 */
@Route(path = RouterPath.PATH_MAIN_PAGE)
@AndroidEntryPoint
class MainActivity : BaseMvvmActivity<ActivityMainBinding>() {

    //定义需要哪些用户权限
    private val needUserPermission = arrayListOf(
        Manifest.permission.CAMERA,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.READ_PHONE_NUMBERS,
        Manifest.permission.ACCESS_FINE_LOCATION
    )

    //用户没有同意的权限
    private val unGrantPermission = arrayListOf<String>()


    override fun getLayoutId(): Int = R.layout.activity_main
    val title = arrayOf("首页","服务", "消息", "公告", "我的")
    val icons = intArrayOf(R.drawable.home,R.drawable.server,R.drawable.message,R.drawable.notice,R.drawable.mine)
    val icons1 = intArrayOf(R.drawable.home1,R.drawable.server1,R.drawable.message1,R.drawable.notice1,R.drawable.mine1)

    override fun initViews() {
        mDataBinding.vp.adapter = MainPageAdapter(this)
        val tabEntity = ArrayList<CustomTabEntity>()
        for (i in title.indices){
            tabEntity.add(TabEntity(title[i],icons1[i],icons[i]))
        }
        mDataBinding.tab.setTabData(tabEntity)
        mDataBinding.tab.setOnTabSelectListener(object :OnTabSelectListener{
            override fun onTabSelect(position: Int) {
                mDataBinding.vp.currentItem = position
            }

            override fun onTabReselect(position: Int) {

            }

        })

        mDataBinding.vp.registerOnPageChangeCallback(object :ViewPager2.OnPageChangeCallback(){
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                mDataBinding.tab.currentTab = position
            }
        })

        //自动发起权限授权
        autoRequestPermission()

    }

    /**
     * 处理其他业务发送过来的事件
     */

    override fun handEvent(event: CustomEvent) {
        when(event.type){
            //有新的消息
            100->{
                //设置公告提示


            }
            //有新的公告信息
            101->{
                //设置公告提示

            }
        }
    }


    /**
     * 使用RxPermission发起用户权限授权
     */

    private fun autoRequestRxPermission(){

    }


    private fun autoRequestPermission(): Boolean {

        //判断系统版本，只有在6.0以后才需要动态授权
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            //清理一下未授权的用户权限
            unGrantPermission.clear()
            //查找还未授权的用户权限
            needUserPermission.forEach {
                //检查当前权限是否被用户同意
                var permissionState= checkSelfPermission(it)
                if (permissionState==PackageManager.PERMISSION_DENIED){//未授权
                    unGrantPermission.add(it)
                }
            }

            //发起授权
            if (unGrantPermission.size>0){
                requestPermissions(unGrantPermission.toTypedArray(),102)
                return false
            }
        }
        return true
    }


    /**
     * 权限授权返回
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        var hasUnGranted = false
        if (requestCode==102 && Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
            unGrantPermission.forEach {
                //判断用户取消的权限
                if (checkSelfPermission(it) == PackageManager.PERMISSION_DENIED){
                    hasUnGranted = true
                }
            }
        }
        //弹窗告诉用户去设置中心的应用详情里的设置
        if (hasUnGranted){
            val builder = AlertDialog.Builder(this@MainActivity)
            builder.setTitle("权限申请")
                .setMessage("没有授权，请去设置中心打开权限")
                .setPositiveButton("去设置"){dialog,which->
                    dialog.dismiss()
                    openSettingsAppDetail()
                    hasUnGranted = false
                }
                .setNegativeButton("取消"){dialog,which->
                    dialog.dismiss()
                    hasUnGranted = false
                }.show()
        }
    }

    private fun openSettingsAppDetail(){
        var intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.fromParts("pachage",packageName,null)
        this@MainActivity.startActivity(intent)
    }
}


